package xyz.lwm.lazycat.transaction;

import xyz.lwm.lazycat.transaction.execute.TranDefinition;
import xyz.lwm.lazycat.transaction.policy.TransactionPolicy;
import xyz.lwm.lazycat.transaction.policy.TransactionPolicy.CheckedRunnable;
import xyz.lwm.lazycat.transaction.policy.TransactionPolicy.CheckedSupplier;

/**
 * 事务调用工具, 可以直接调用方法, 效果同 {@link xyz.lwm.lazycat.transaction.Transactional}
 *
 * @author lwm
 */
public abstract class TransactionUtil {

    /**
     * 执行事务, 无返回结果
     *
     * @param tranDefinition 事务定义
     * @param runnable       业务逻辑
     */
    public static void exec(TranDefinition tranDefinition, CheckedRunnable runnable) throws Throwable {
        execute(tranDefinition, () -> {
            runnable.run();
            return null;
        });
    }

    /**
     * 执行事务
     *
     * @param tranDefinition 事务定义
     * @param supplier       业务逻辑
     * @param <T>            业务逻辑返回结果类型
     * @return 业务逻辑返回结果
     */
    public static <T> T execute(TranDefinition tranDefinition, CheckedSupplier<T> supplier) throws Throwable {
        return TransactionPolicy.getPolicy(tranDefinition).execute(supplier);
    }

}
